package com.lzx.adx.report.controller.v1.tencent;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.GtdResult;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.tencent.request.GTdCallBackRequest;
import com.lzx.adx.report.model.tencent.request.TencentReportRequest;
import com.lzx.adx.report.model.tencent.request.callback.Params;
import com.lzx.adx.report.model.tencent.request.callback.UserInfo;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.AdPerUtil;
import com.lzx.adx.report.util.UrlUtil;
import com.lzx.adx.report.util.helper.KkHeper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * 媒体：广点通
 * 产品：京东金融
 */
@RestController
@RequestMapping("/gdt/kk")
@Slf4j
public class TencentKKReportController {


    @Resource
    private ReportService reportService;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;


    @GetMapping("/report")
    public ResponseEntity report(TencentReportRequest tencentReportRequest) {
        log.info("广点通到夸克的参数为{}", JSON.toJSONString(tencentReportRequest));
        ReportDTO reportDTO = reportMapper.toReportGTdDTO(tencentReportRequest);
        reportDTO.setBizRequestId(IdUtil.fastUUID());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JSON.toJSONString(tencentReportRequest));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        reportDTO.setOaidSum(tencentReportRequest.getHash_oaid());
        reportDTO.setOaid(null);
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(tencentReportRequest.getDspId());
        //获取配置信息
        //3.处理参数和URL
        String resultUrl = KkHeper.covertHwKk(accountDTO, reportDTO);
        log.info("账户号为{}完整的广点通到夸克请求地址为{}", tencentReportRequest.getDspId(), resultUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(resultUrl).execute().body();
        log.info("账户号为{}广点通到夸克的接口 响应的结果为{}", tencentReportRequest.getDspId(), body);
        return ResponseEntity.ok(new Result());
    }


    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId) throws Exception {
        String evenType="1";
        log.info("接收了夸克到广点通回调信息，请求流水号{}", requestId);
        if (StringUtils.isBlank(requestId)) {
            log.info("接收了夸克到广点通回调信息 流水号空");
            return ResponseEntity.ok(new Result());
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        long time = System.currentTimeMillis();
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(evenType);
            reportDTO.setResultTime(String.valueOf(time));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,evenType);
        } else {
            log.error("回传流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        //如果不为空，且sspExtend
        if(StringUtils.isNotBlank(sspExtend)){
            JSONObject jsonObject = JSONObject.parseObject(sspExtend);
            Double per = jsonObject.getDouble("per");
            if(Objects.nonNull(per)){

                if(!AdPerUtil.randomPer(per)){
                    return ResponseEntity.ok(new Result());
                }
            }
        }

        TencentReportRequest tencentReportRequest= JSON.parseObject(reportDTO.getExtend(),TencentReportRequest.class) ;
        //2.回调渠道，调用腾讯回传接口
        UserInfo userInfo = new UserInfo();
        userInfo.setHash_oaid(tencentReportRequest.getHash_oaid());
        userInfo.setHash_imei(tencentReportRequest.getMuid());
        userInfo.setHash_android_id(tencentReportRequest.getHash_android_id());
        Params params1 = new Params();
        params1.setAction_time(time / 1000);
        params1.setAction_type("ACTIVATE_APP");
        params1.setOuter_action_id(reportDTO.getBizRequestId());
        params1.setUser_id(userInfo);
        params1.setAction_param(new HashMap<>());
        GTdCallBackRequest gTdCallBackRequest = new GTdCallBackRequest();
        gTdCallBackRequest.setActions(Lists.newArrayList(params1));
        String paramsBody = JsonUtils.toJsonString(gTdCallBackRequest);
        log.info("账号为{} 请求流水号{}夸克给广点通回调的请求的参数为{}", reportDTO.getDspId(), requestId, paramsBody);
        String url = URLUtil.decode(reportDTO.getCallback());
        HttpRequest body = HttpUtil.createPost(url).body(paramsBody);
        String result = body.execute().body();
        log.info("账号为{} 请求流水号{}夸克给广点通上报接广点通转换响应的结果为{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new GtdResult<>());

    }




}
